package com.li.client.management;

import java.util.ArrayList;
import java.util.List;

import com.li.client.entities.BookInfo;
import com.li.client.service.DataServiceFactory;
import com.li.client.util.GwtCallBack;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;

public class AllBookInfoManager extends VLayout {
	private ListGrid grid;
	private DataSource ds;
	
	private VLayout layout;
	
	public AllBookInfoManager() {
		init();
	}
	
	private void init() {
		initGrid();
		populateData();
		
		layout = new VLayout();
		layout.addMember(grid);
		
		addMember(layout);
	}
	
	private void initGrid() {
		grid = new ListGrid();
		grid.setWidth("50%");
		grid.setHeight("50%");
		grid.setFields(getGridFields().toArray(new ListGridField[0]));
	}
	
	private void populateData() {
		ds = new BookInfoDataSource();
		grid.setDataSource(ds);
		grid.fetchData();
	}
	
	private List<ListGridField> getGridFields() {
		List<ListGridField> fields = new ArrayList<ListGridField>();
		
		return fields;
	}
	
	private class BookInfoDataSource extends LibGridDataSource {

		@Override
		protected void createDataSourceFields() {
			DataSourceField bookName = new DataSourceField("bookName", FieldType.TEXT, "Name");
			DataSourceField isbnCode = new DataSourceField("isbnCode", FieldType.TEXT, "ISBN");
			DataSourceField inStock = new DataSourceField("inStock", FieldType.INTEGER, "In Stock");
			
			setFields(bookName, isbnCode, inStock);
		}

		@Override
		protected void executeFetch(String requestId, final DSRequest request,
				final DSResponse response) {
			DataServiceFactory.getService().getAllBookInfo(new GwtCallBack<List<BookInfo>>() {

				@Override
				protected void onResult(List<BookInfo> result) {
					if (result == null || result.size() == 0) {
						setNullRecords(request, response);
						return;
					}
					
					RecordList list = new RecordList();
					ListGridRecord record;
					
					for (BookInfo bookInfo : result) {
						record = new ListGridRecord();
						
						record.setAttribute("bookName", bookInfo.getBookName());
						record.setAttribute("isbnCode", bookInfo.getIsbnCode());
						record.setAttribute("inStock", bookInfo.getInStock());
						
						list.add(record);
					}
					
					response.setData(list.toArray());
					response.setTotalRows(list.getLength());
					processResponse(request.getRequestId(), response);
				}
			});
		}
		
	}
}
